import {app, $$} from "../experience/utils/F7.js";
import {CONF} from "../configure/Assets.js"
import Db from "../experience/db/Db.js";
import Api from "../experience/api/Api.js";
import Utils from "../experience/utils/Utils.js";
import zTreeUtils from "../experience/utils/zTreeUtils.js";
import Algorithm from "../experience/utils/Algorithm.js";
import Drawer from "../experience/drawer/Drawer.js";
import Selector from "../component/other/Selector.js";
import Coordinate from "../component/other/Coordinate.js";
import Measure from "../component/other/Measure.js";
import Route from "../component/route/Route.js";
import WarningV2 from "../component/warning/WarningV2.js";
import Monitor from "../component/monitor/Monitor.js";
import zTreeAdmin from "../component/ztree/ztreeAdmin.js"
import zTreeData from "../component/ztree/ztreeData.js"
import smUploader from "../component/ztree/smUploader.js"
import SensorRelationAlarm from "../component/smRelationAlarm/sensorRelationAlarm.js"
import VentilationArrowRender from "../component/smVentilationArrowRender/ventilationArrowRender.js"
import PoweredAreaEdit from "../component/smPoweredArea/poweredArea_Edit.js"
import LayerViewer from "../component/smMetaLayer/LayerViewer.js"
import LayerEditColor from "../component/smMetaLayer/LayerEditColor.js"
import PoweredAreaPreview from "../component/smPoweredArea/poweredArea_Preview.js"
import {ServiceType,LayerType} from "../experience/db/SafeMonitorType.js";
class safeMonitor {
    constructor() {
        if (safeMonitor.instance) {
            return safeMonitor.instance;
        }
        safeMonitor.instance = this;

        this.db = new Db();
        this.api = new Api();
        this.utils = new Utils();
        this.algo = new Algorithm();
        this.drawer = new Drawer();
        this.ztreeUtils = new zTreeUtils()
        this.RelationAlarm = new SensorRelationAlarm()
        new VentilationArrowRender()
        let edit = this.utils.getUrlParamer("edit");
        let mode = this.utils.getLocalStorage("mode");
        this.init().then(() => {
            this.header(edit);

            if (edit == 'true') {
                new zTreeAdmin();
                new smUploader();
                new Coordinate();
                new Selector();
                // 隐藏 编辑模式下的断点区域的相关功能
                // new PoweredAreaEdit()
                // 添加距离测量功能组件
                new Measure()
                new LayerEditColor()
                // new Monitor();
                // 修改Uploader提示信息
                $$("#upload-name-text").html("图纸版本");
                $$("#upload-code-text").html("图纸类型");
                $$("#upload-mine-code").val(mode);
            } else {
                this.timer();
                new zTreeData()
                new Measure()
                new LayerViewer()
                // 将断电区域的相关功能额隐藏掉
                // new PoweredAreaPreview()
                const route = this.utils.getLocalStorage("route");
                if (mode === "person") {
                    new Selector();
                    new Measure();
                    new WarningV2();
                    new Monitor();
                } else {
                    if (route) {
                        new Route();
                    } else {
                        new Selector();
                        new Measure();
                    }
                }
            }
            console.log("Walküre Fly...");
        });
    }

    header(edit) {
        if (edit) {
            // 在编辑模式下需要添加操作header
            const upload_div = `<div id="upload-popup" class="GisUtilIcon" style="position: absolute;top: 50px;left: 25px;z-index: 999"><i class="fas fa-upload" /></div>`
            $$("body").append(upload_div);
            $$("#upload-mine-code").attr("readonly", "readonly");
        } else {
            const selectLayer_btn = `<div id="layerselect-popup" class="GisUtilIcon" style="position: absolute;top: 50px;left: 25px;z-index: 999"><i class="fas fa-layer-group"></i></div>`
            $$("body").append(selectLayer_btn);
            $$("#vehicle-locked-unlocked").hide();
        }
    }

    timer() {
        const mode = this.utils.getLocalStorage("mode");

        // 点击下载新图纸
        $$("#get-tree-maps").on("click", async () => {
            const metas = await this.api.getMetas(mode);
            if (metas.code === 0 && metas.data.length > 0) {
                await this.update(metas.data[0]);
            }
        });
        const refreshTime = 1000 * 60 * 2
        // const refreshTime = 8000
        // 一分钟判断一次是否版本有更新
        setInterval(async () => {
            const config = this.algo.getConfig();
            // 每分钟都进行 一次indexDb里面的 安全监控相关的表格信息更新
            this.ztreeUtils.PositionDbRefresh()
            if (config === null) return;

            const srcVer = config.mine_name;
            const metas = await this.api.getMetas(mode);
            const cmpVer = metas.data[0].mine_name;
            if (srcVer !== cmpVer) {
                $$("#get-tree-maps").show();
            }
        }, refreshTime);
    }

    async update(meta) {
        try {
            const meta_id = meta.meta_id;
            app.dialog.preloader("正在同步数据...");
            const data = await this.api.getVector(meta_id);
            const sm_data = await this.api.getSmPositions(ServiceType.Mine_Id)
            data.data.entities.smgas = sm_data.data.filter((el) => {
                return el.layer == LayerType.SMGas
            })
            data.data.entities.smstaff = sm_data.data.filter((el) => {
                return el.layer == LayerType.SMStaff
            })
            data.data.entities.smbroadcast = sm_data.data.filter((el) => {
                return el.layer == LayerType.SMBroadCast
            })
            data.data.entities.smvideo = sm_data.data.filter((el) => {
                return el.layer == LayerType.SMVideo
            })
            if (data.code === 0) {
                // 初始化config信息
                this.drawer.init(data.data.meta, data.data.layers);
                // 将从网络上取下来的数据存入数据库
                this.db.init(data.data).then(() => {
                    // 从本地提取数据
                    this.drawer.location().then(() => {
                        const config = this.algo.getConfig();
                        config.maxzoom = 14;
                        config.minzoom = 4;
                        this.algo.setConfig(config);
                        $$("#get-tree-maps").hide();
                        app.dialog.close();
                        this.drawer.createControl()
                    });
                });
            }
        }
        catch (e) {
            console.log('捕获到了异常')
        }

    }

    // 全局初始化
    async init() {
        // 初始化 设备选择 断点区域按钮的行为
        $("#equipSelect").on('click',function (event) {
            const dom = document.querySelector('#eqDialog')
            const height = dom.clientHeight
            if(height > 0) {
                dom.style.height = 0
            } else {
                dom.style.height = 'auto'
            }
        })
        const map = this.drawer.map
        map.lastZoom = map.lastZoom || map.getView().getZoom()
        map.on('moveend',() => {
            const currentZoom = map.getView().getZoom()
            if(currentZoom != map.lastZoom) {
                if(currentZoom > 9) {
                    // 显示 通风系统的图层
                    this.drawer.drawer.SMVentilate.setVisible(true)
                    // 显示通风系统动画图层
                    this.drawer.drawer.SMVentilateAnimation.setVisible(true)
                }
                else {
                    // 隐藏通风系统的图层
                    this.drawer.drawer.SMVentilate.setVisible(false)
                    // 隐藏通风系统动画的图层
                    this.drawer.drawer.SMVentilateAnimation.setVisible(false)
                }
                if(currentZoom < 7) {
                    // 开启聚合图层，并隐藏其他安全监控元素图层
                    this.drawer.drawer.SMGas.setVisible(false)
                    this.drawer.drawer.SMStaff.setVisible(false)
                    this.drawer.drawer.SMBroadCast.setVisible(false)
                    this.drawer.drawer.SMCluster.setVisible(true)
                }
                else {
                    // 关闭聚合图层,并开启其他安全监控元素图层
                    this.drawer.drawer.SMGas.setVisible(true)
                    this.drawer.drawer.SMStaff.setVisible(true)
                    this.drawer.drawer.SMBroadCast.setVisible(true)
                    this.drawer.drawer.SMCluster.setVisible(false)
                }
                map.lastZoom = currentZoom

            }
        })
        $("#vehicle-locked-unlocked").hide();
        this.utils.setLocalStorage("theme", false);

        // 获取配置用的code信息
        const code = await this.api.getCode();
        this.utils.setLocalStorage('code', code.data);
        // 初始化 断电区域 选择器的状态
        this.utils.setLocalStorage('PA_select_status', false);
        // 从参数中获取模式: person - 人员定位, vehicle - 车辆定位
        let mode = this.utils.getUrlParamer("mode"), loading = false;
        if (mode === "embed" || mode === "vehicle") {
            this.utils.setLocalStorage("theme", true);
            $$(".ol-viewport").css("background", CONF.BACKGROUND);
            mode = "vehicle";
        } else {
            this.utils.setLocalStorage("theme", true);
            $$(".ol-viewport").css("background", CONF.BACKGROUND);
            mode = "person";
        }

        // 如果原来已经设置过模式,则需要和本地进行比较,如果不同则需要重新获取数据
        const localMode = this.utils.getLocalStorage("mode");
        if (localMode !== null && localMode !== mode) {
            loading = true;
        }
        this.utils.setLocalStorage("mode", mode);

        // 从参数中获取是否为编辑模式
        let edit = this.utils.getUrlParamer("edit");
        if (edit === null || edit !== "true") {
            this.utils.setLocalStorage("edit", false);
        } else {
            this.utils.setLocalStorage("edit", true);
        }

        // 从参数中获取是否为Route模式
        let route = this.utils.getUrlParamer("route");
        if (route === null || route !== "true") {
            this.utils.setLocalStorage("route", false);
        } else {
            this.utils.setLocalStorage("route", true);
        }

        // 从参数中获取vehicleid
        let vehicleId = this.utils.getUrlParamer("vehicleid");
        this.utils.setLocalStorage("vehicleId", vehicleId);

        const config = this.algo.getConfig();
        const metas = await this.api.getMetas(mode);

        // 判断本地indexDb中是否已经存在我们的valkyrja数据库是否已经存在
        const dbs = await window.indexedDB.databases('valkyrja')
        const isExist = dbs.some((db) => {
            return db.name == 'valkyrja'
        })
        if (!isExist) {
            await this.update(metas.data[0]);
        }
        else {
            // 还得先判断 图纸的版本是否发生了变化
            const {data:metas} = await this.api.getMetas(ServiceType.Meta_Id)
            const current_meta_v = metas[0].mine_name
            const {mine_name:old_meta_v} = await this.db.operation('meta','get',metas[0].id)
            // 图纸版本不一致 就更新
            if(current_meta_v != old_meta_v) {
                this.update(metas[0])
            }
            else {
                // 从本地获取数据
                this.drawer.location().then(() => {
                    // 前面构建完成之后，创建 鹰眼视图ter
                    this.drawer.createControl()
                })
            }
        }
        // 给一个默认的zoom
        this.drawer.map.getView().setZoom(6)
    }
}

new safeMonitor();